package com.bytech.gateway.config;

import java.util.List;
import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.bytech.common.biz.entity.system.route.MyVersionableRouteConfigInfo;
import com.bytech.common.config.AppGlobalConstants;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.config.GatewayAutoConfiguration;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.bytech.common.utils.JedisClient;
import com.bytech.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 网关动态路由组件
 * 通过注入 RouteDefinitionRepository 这个bean来重写获取路由信息方法以达到动态刷新路由的目的
 *
 * @Author zhao
 * @Create 2021/7/27 11:35
 * @see GatewayAutoConfiguration
 */
@Component
@Slf4j
public class RedisRouteDefinitionRepository implements RouteDefinitionRepository {

    @Resource
    private JedisClient jedisClient;

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        String json = jedisClient.go((cluster) -> cluster.get(AppGlobalConstants.GATEWAY_ROUTES_KEY));
        if (StringUtils.isBlank(json)) {
            return null;
        }
        try {
            log.info("gateway routes update with route info :" + json);
            JSONObject object = JSON.parseObject(json);
            String rsInfo = object.getString("routeDefinitions");
            List<RouteDefinition> rs = JSON.parseArray(rsInfo, RouteDefinition.class);
            return Flux.fromIterable(rs);
        } catch (Exception e) {
            log.info("deserialize route json failed,setting gateway route info to null...");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return null;
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return null;
    }

}
